package rules.tree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jdom.Element;

public class Body {

	private Element body;
       // private Atom a;
        private Context c;
        private List<Atom> listAtom;

	public Body(Element body) {
		this.body = body;
                this.listAtom = getListAtom(body); 
                this.c = getContext(body);
	}

        public Body() {
		this.body = new Element("body");
                this.listAtom = new ArrayList<Atom>();
                this.c = getContext(body);
	}

       public void addAtom(Atom a){
            listAtom.add(a);
            body.addContent(a.getElement());
       }

	public Element getBody() {
		return body;
	}

	public boolean hasContext() {
		List temp = body.getChildren();
		Iterator it = temp.iterator();
		while (it.hasNext()) {
			if (((Element) it.next()).getName().equals("context"))
				return true;
		}
		return false;
	}

        private static Context getContext(Element el){
            List temp = el.getChildren();
            Element c;
		Iterator it = temp.iterator();
		while (it.hasNext()) {
			if ((c=((Element) it.next())).getName().equals("context"))
				return new Context(c);
		}
                return null;
        }

	private static Atom getAtom(Element el) {
		Atom atom = new Atom(el);
		String type = atom.getTypeAtom();
		if (type.equals("classAtom"))
			return atom.getClassAtom();
		else if (type.equals("propertyAtom"))
			return atom.getPropertyAtom();
		else if (type.equals("builtinAtom"))
			return atom.getBuiltinAtom();
		return null;
	}

      /*  public Atom getAtom(){
            return a;
        }*/

	public List<Atom> getListAtom() {
		return listAtom;
        }

        private static ArrayList<Atom> getListAtom(Element body) {
		List temp = body.getChildren();
		Iterator it = temp.iterator();
		Atom o = null;
		ArrayList<Atom> list = new ArrayList();
		while (it.hasNext()) {
			o = getAtom((Element) it.next());
			if(o!=null)list.add(o);
		}
		return list;
	}
	
	public Context getContext(){
		return c;
	}

        public void setContext(Context c){
            body.addContent(c.getElement());
            this.c = c;
	}
}
